﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using Wallpaper.Data.Context;
using Wallpaper.Data.IDal;
using Wallpaper.Models.DTOs.WeChatLogin;
using Wallpaper.Models.DTOs.WeChatLogin.Responses;
using Wallpaper.Models.Entities;
using Wallpaper.Services.IService;

namespace Wallpaper.Services.Service
{
    public class WeChatService : IWeChatService
    {
        private readonly HttpClient _httpClient;
        private readonly IConfiguration _configuration;
        private readonly IUserDal _userDal;
        readonly WallpaperDbContext _wallpaperDbContext;

        public WeChatService(HttpClient httpClient, IConfiguration configuration, IUserDal userDal, WallpaperDbContext wallpaperDbContext)
        {
            _httpClient = httpClient;
            _configuration = configuration;
            _userDal = userDal;
            _wallpaperDbContext = wallpaperDbContext;
        }


        public async Task<WeChatLoginResult> CodeToSessionAsync(string code)
        {
            var appId = _configuration["WeChat:AppId"];
            var appSecret = _configuration["WeChat:AppSecret"];

            var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code";

            var response = await _httpClient.GetFromJsonAsync<WeChatSessionResponse>(url);

            if (string.IsNullOrEmpty(response.OpenId))
                throw new Exception($"微信登录失败: {response.ErrorCode} - {response.ErrorMessage}");

            return new WeChatLoginResult
            {
                OpenId = response.OpenId,
                SessionKey = response.SessionKey,
                UnionId = response.UnionId
            };
        }


        public async Task<User> GetOrCreateUserAsync(WeChatLoginResult wechatInfo, string ipAddress, string nickname = null, string avatarUrl = null)
        {
            // 查找已存在用户
            var existingUser = await _wallpaperDbContext.Users
                .FirstOrDefaultAsync(u => u.OpenId == wechatInfo.OpenId);

            if (existingUser != null)
            {
                // 更新最后登录信息和用户资料
                existingUser.LastLoginTime = DateTime.Now;
                existingUser.IPAddress = ipAddress;
                existingUser.UpdatedAt = DateTime.Now;

                // 如果提供了新的昵称和头像，更新它们
                if (!string.IsNullOrEmpty(nickname))
                    existingUser.Nickname = nickname;
                if (!string.IsNullOrEmpty(avatarUrl))
                    existingUser.AvatarUrl = avatarUrl;

                await _wallpaperDbContext.SaveChangesAsync();
                return existingUser;
            }

            // 创建新用户 - 使用用户选择的昵称和头像
            var newUser = new User
            {
                Id = Guid.NewGuid().ToString(),
                OpenId = wechatInfo.OpenId,
                Nickname = nickname ?? $"微信用户_{DateTime.Now:yyyyMMddHHmmss}", 
                Gender = "unknown",
                AvatarUrl = avatarUrl ?? "", 
                Points = 0,
                TodayFreeDownloadCount = 3,
                LastDownloadDate = DateTime.Now,
                IPAddress = ipAddress,
                LastLoginTime = DateTime.Now,
                CreatedAt = DateTime.Now,
                IsEnabled = true,
                IsDeleted = false
            };
            await _wallpaperDbContext.Users.AddAsync(newUser);
            await _wallpaperDbContext.SaveChangesAsync();
            return newUser;
        }
    }
}
